package com.mocchira.music.radio;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView.OnEditorActionListener;

public class HotTagsPlayListActivity extends Activity implements OnItemClickListener, OnItemSelectedListener {
    
    private EditText edit;
    private ListView artistList;
    private Spinner tagSpinner;
    
    private HotTagsManager manager;
    private String encTag;
    private ArrayAdapter<String> adapter;
    
    private ProgressDialog progress = null;
    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONArray hotList = manager.getHotArtistsByTag(encTag);
            if (hotList == null) {
                this.sendEmptyMessageDelayed(0, 1000);
                return;
            }
            List<String> result = new ArrayList<String>();
            for (int i = 0; i < hotList.length(); i++) {
                try {
                    String artist = hotList.getString(i);
                    result.add(artist);
                } catch (Exception ex) {};
            }
            if (result.size() == 0) return;
            Collections.sort(result);
            String[] array = new String[1];
            adapter = new ArrayAdapter<String>(HotTagsPlayListActivity.this, android.R.layout.simple_list_item_1, result.toArray(array));
            artistList.setAdapter(adapter);
            if (progress.isShowing())
                try {progress.dismiss();}catch (Exception nex){};
        }
    };

    private TextWatcher filterTextWatcher = new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (adapter != null)
                adapter.getFilter().filter(s);
        }

    };
    
    private ArrayAdapter<String> genTagArrayAdapter(JSONArray selectableTags) {
        String[] ret = new String[selectableTags.length()];
        for (int i = 0; i < selectableTags.length(); i++) {
            try {
                String tmp = selectableTags.getString(i);
                ret[i] = URLDecoder.decode(tmp, "UTF-8");
            } catch(Exception ex) {continue;};
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ret);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        return adapter;
    }
    
    private int getInitialSpinnerPos(JSONArray selectableTags, String tag) {
        for (int i = 0; i < selectableTags.length(); i++) {
            try {
                String tmp = selectableTags.getString(i);
                tmp = URLDecoder.decode(tmp, "UTF-8");
                if (tmp.equals(tag))
                    return i;
            } catch(Exception ex) {continue;};
        }
        return -1;
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        if (bundle == null)
            return; // nothing to do for dummy
        encTag = (String)bundle.get(R.string.bundle_artist + "");
        if (encTag == null || encTag.length() == 0)
            return; // nothng to do for dummy
        setContentView(R.layout.hottag);
        artistList = (ListView)findViewById(R.id.artistList);
        artistList.setOnItemClickListener(this);
        artistList.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodManager imm = 
                    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(edit.getWindowToken(),0);
                return false;
            }
        });
        edit = (EditText)findViewById(R.id.filterEdit);
        edit.addTextChangedListener(filterTextWatcher);
        edit.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                InputMethodManager imm = 
                    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(edit.getWindowToken(),0);
                return true;
            }
        });
        manager = HotTagsManager.getInstance(this);
        JSONArray selTags = manager.getSelectableTags();
        tagSpinner = (Spinner)findViewById(R.id.tagSpinner);
        tagSpinner.setAdapter(genTagArrayAdapter(selTags));
        tagSpinner.setSelection(getInitialSpinnerPos(selTags, encTag));
        tagSpinner.setOnItemSelectedListener(this);
        manager.getHotArtistsByTag(encTag);
        handler.sendEmptyMessageDelayed(0, 1);
        if (progress == null)
            progress = ProgressDialog.show(HotTagsPlayListActivity.this, "preparing...", "Download Artist List File");
    }
    
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        Intent intent = new Intent(this, FMRPlayActivity.class);
        Bundle bundle = new Bundle();
        String artist = (String)arg0.getItemAtPosition(position);
        bundle.putString(R.string.bundle_artist+"", artist);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
        encTag = (String)parent.getAdapter().getItem(position);
        manager.getHotArtistsByTag(encTag);
        TextView tv = (TextView)((TabActivity)this.getParent()).getTabHost().getCurrentTabView().findViewById(android.R.id.title);
        tv.setText(encTag);
        handler.sendEmptyMessageDelayed(0, 1);
        if (progress == null)
            progress = ProgressDialog.show(HotTagsPlayListActivity.this, "preparing...", "Download Artist List File");
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        ;
    }

}
